// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, sort_child_properties_last
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:junyeyishu/mianTab.dart';
import 'package:junyeyishu/ui/login/QGCatchVerifyAliPage.dart';

import "package:junyeyishu/utils/utils.dart";
import 'package:junyeyishu/widgets/QGCircleCheckWidget.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';

class QGLoginPasswordPage extends StatefulWidget {
  const QGLoginPasswordPage({super.key});
  @override
  State<QGLoginPasswordPage> createState() => _QGLoginPasswordPageState();
}

class _QGLoginPasswordPageState extends State<QGLoginPasswordPage> {
  bool check = true;
  bool isShowPassword = true;
  final phoneController = TextEditingController(text: '18420053587');
  final passwordController = TextEditingController();

  @override
  void dispose() {
    phoneController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        buildText("账号密码登录", 26.rpx, FontWeight.bold, 0xFF111111),
        SizedBox(height: 3.rpx),
        buildText("使用已经注册过的手机号登录", 14.rpx, FontWeight.normal, 0xFF111111),

        SizedBox(height: 15.rpx),
        Container(
          margin: EdgeInsets.symmetric(horizontal: 20.rpx),
          padding: EdgeInsets.symmetric(horizontal: 20,vertical: 20),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            color: Color(0XB3FFFFFF)
          ),
          child: Column(
            children: [
              buildPhone(),
              SizedBox(height: 15.rpx),
              buildPassword(),
              SizedBox(height: 20.rpx),
              buildButton(),
            ])),


        
        SizedBox(height: 15.rpx),
        buildAgreement(),
      ],
    );
  }

  buildText(text, fontSize, fontWeight, color) {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(left: 25.rpx),
      child: Text(
        text,
        style: TextStyle(
            fontSize: fontSize, fontWeight: fontWeight, color: Color(color)),
      ),
    );
  }

  buildPhone() {
    return Row(
      children: [
        Expanded(
            child: Container(
          height: 54.rpx,
          decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(
                  color: Color(0XFFA6D9D4)
                )
              ),
           ),
          child: Padding(
                       padding: EdgeInsets.only(left: 5.rpx, right: 5.rpx),

            child: Row(
              children: [
                Expanded(
                  child: TextField(
                      controller: phoneController,
                      keyboardType: TextInputType.number,
                      textInputAction: TextInputAction.done,
                      cursorColor: Color(0xFF111111),
                      style: TextStyle(
                          color: Color(0xFF111111),
                          fontSize: 13.rpx,
                          fontWeight: FontWeight.bold),
                      decoration: InputDecoration(
                        hintText: "请输入手机号",
                        hintStyle: TextStyle(
                            color: Color(0xFF739D98),
                            fontWeight: FontWeight.normal), //修改颜色
                        enabledBorder: InputBorder.none,
                        focusedBorder: InputBorder.none,
                      )),
                ),
              ],
            ),
          ),
        )),
      ],
    );
  }

  buildPassword() {
    return Row(
      children: [
        Expanded(
          child: Container(
            alignment: Alignment.centerLeft,
            height: 52.rpx,
            padding: EdgeInsets.only(left: 5.rpx, right: 5.rpx),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color(0XFFA6D9D4)
                )
              ),
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: passwordController,
                    keyboardType: TextInputType.text,
                    cursorColor: Color(0xFF111111),
                    textAlignVertical: TextAlignVertical.center,
                    obscureText: isShowPassword,
                    obscuringCharacter: '*',
                    style: TextStyle(
                      fontSize: 13.rpx,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF111111),
                      textBaseline: TextBaseline.alphabetic,
                    ),
                    decoration: InputDecoration(
                        hintText: '请输入密码(最少8位,数字+字母)',
                        hintStyle: TextStyle(
                            color: Color(0xFF739D98),
                            fontWeight: FontWeight.normal),
                        isCollapsed: true,
                        border: OutlineInputBorder(borderSide: BorderSide.none),
                        enabledBorder: InputBorder.none,
                        focusedBorder: InputBorder.none),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    isShowPassword = !isShowPassword;
                    if (mounted) {
                      setState(() {});
                    }
                  },
                  child: isShowPassword
                      ? QGImage(asset: "mine_password_close")
                      : QGImage(asset: "mine_password_open"),
                )
              ],
            ),
          ),
        ),
      ],
    );
  }

  buildButton() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 50.rpx,
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [Color(0xFF4AE3FF), Color(0xFF44FFF0)],
              ),
              borderRadius: BorderRadius.circular(25.rpx),
            ),
            child: TextButton(
              onPressed: () {
                                toLogin();

              },
              child: Text(
                '登录1',
                style: TextStyle(
                    color: Color(0xFF111111),
                    fontSize: 16.rpx,
                    fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ),
      ],
    );
  }

  buildAgreement() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        QGCircleCheckWidget(
            size: 12.rpx,
            select: check,
            padding: EdgeInsets.symmetric(vertical: 5.rpx, horizontal: 5.rpx),
            image: "login_checks",
            onTap: (select) {
              check = select;
              setState(() {});
            }),
        SizedBox(width: 3.rpx),
        Text(
          '已阅读并同意',
          style: TextStyle(
              color: Color(0xFF666666),
              fontSize: 12.rpx,
              fontWeight: FontWeight.normal),
        ),
        GestureDetector(
          onTap: onAgreement,
          child: Container(
            color: Colors.transparent,
            padding: EdgeInsets.symmetric(vertical: 10.rpx),
            child: Text(
              "《用户服务协议》",
              style: TextStyle(
                fontSize: 12.rpx,
                color: Color(0xFF5E85E3),
              ),
            ),
          ),
        ),
        GestureDetector(
          onTap: onPrivacy,
          child: Container(
            color: Colors.transparent,
            padding: EdgeInsets.symmetric(vertical: 10.rpx),
            child: Text(
              "《用户隐私政策》",
              style: TextStyle(
                fontSize: 12.rpx,
                color: Color(0xFF5E85E3),
              ),
            ),
          ),
        ),
      ],
    );
  }

  toLogin() {
    unfocus(context);
    var ctx = context;

    if (!check) {
      toast("请阅读并同意协议");
      return;
    }

    var phone = phoneController.text;
    var password = passwordController.text;

    if (phone.isEmpty || phone.length != 11) {
      toast("请输入正确手机号");
      return;
    }

    if (password.isEmpty) {
      toast("请输入密码");
      return;
    }

    // showDialog(
    //     context: context,
    //     builder: (context) {
    //       return QGCatchVerifyAliPage(phone: phone);
    //     }).then((value) {
          
      // if (value is! Map) return;

  
     final data = FormData.fromMap({
      "phone":phone,
      "password":password,
      "captchaVerifyParam":"2"
     });

      Network.post(url_password_login, data: data, context: context)
          .then((res) async {
        if (!res.success) {
          
          toast(res.msg);
          return;
        }

        res.data["phone"] = phone;
        await User.login(res.data);
        toast(res.msg);

        eventBus.fire(EventLogin());

        Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => MainTab()), 
        (route) => false // 清除所有历史路由
      );

        // Future.delayed(Duration(seconds: 1), () {
        //   Navigator.of(context).pop();
        // });
      });

    //});
  }

  onAgreement() {
    var args = {
      "title": "用户协议",
      "content": getUserAgreement(),
    };
    Navigator.of(context).pushNamed(PageRule, arguments: args);
  }

  onPrivacy() {
    var args = {
      "title": "隐私政策",
      "content": getPrivacyPolicy(),
    };
    Navigator.of(context).pushNamed(PageRule, arguments: args);
  }
}
